package com.example.tangyee.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.tangyee.R;
import com.example.tangyee.utils.SessionidUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MealFragment extends Fragment {

    private static final String TAG = "MealFragment";

    public static MealFragment newInstance() {
        return new MealFragment();
    }

    private Unbinder mUnbinder;

    @BindView(R.id.tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    List<Fragment> fragments = new ArrayList<>();
    List<String> titles = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_meal, container, false);
        mUnbinder = ButterKnife.bind(this,view);
        initView();

        return view;
    }

    private void initView() {
        // 初始化标题与Fragments
        for (int i = 1; i <= 12; i ++) {
            titles.add((i * 250) + "\n千卡");
            fragments.add(MealFragmentForViewPager.newInstance(i * 250));
        }

        // 初始化ViewPager，并设置Adapter
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            /*
            * getPageTitle(int position)函数是返回当前TabLayout的标签标题的，
            * 当然，也可以不通过PagerAdapter中的这个函数返回，
            * 采用下面的这种方式也可行(有多少个就addTab多少次)：
            *  tabLayout.addTab(tabLayout.newTab().setText("tab 1"));
            * */
            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });

        mViewPager.setOffscreenPageLimit(11);
        // 将 TabLayout 与 ViewPager 关联起来
        mTabLayout.setupWithViewPager(mViewPager);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
